﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using CommonFoundation.DataSource;
using CommonFoundation;
using System.IO;
using HtmlAgilityPack;
using CommonFoundation.DataModel;

namespace WHULive
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LogInWindow : Window
    {
        private CookieContainer cookieContainer;

        public LogInWindow()
        {
            InitializeComponent();

            this.refresh();
        }

        #region fresh
        private void clearInfos()
        {
            this.UserNameTextBox.Text = String.Empty;

            this.UserPasswordBox.Password = String.Empty;

            this.GenTextBox.Text = String.Empty;
        }

        private void getNewGenPhoto()
        {
            try
            {
                this.cookieContainer = new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FilePath.GetInstance().BaseUri);

                request.CookieContainer = this.cookieContainer;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                request = (HttpWebRequest)WebRequest.Create(FilePath.GetInstance().GenPhotoUri);
                request.CookieContainer = this.cookieContainer;

                response = (HttpWebResponse)request.GetResponse();

                using (Stream responseStream = response.GetResponseStream())
                {
                    BitmapImage image = new BitmapImage();

                    image.BeginInit();

                    image.StreamSource = this.convertToMemoryStream(responseStream);
                    image.EndInit();

                    this.GenImage.Source = image;
                }
            }
            catch (WebException ex)
            {
                Log.WriteLog(ex.Message);
            }
        }

        private MemoryStream convertToMemoryStream(Stream stream)
        {
            int BytesToRead = 100;

            BinaryReader reader = new BinaryReader(stream);
            MemoryStream memoryStream = new MemoryStream();

            byte[] bytebuffer = new byte[BytesToRead];
            int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

            while (bytesRead > 0)
            {
                memoryStream.Write(bytebuffer, 0, bytesRead);
                bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
            }

            memoryStream.Seek(0, SeekOrigin.Begin);

            return memoryStream;
        }

        private void refresh()
        {
            clearInfos();

            getNewGenPhoto();
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            this.refresh();
        }

        private void LogInButton_Click(object sender, RoutedEventArgs e)
        {
            BindingSource.GetInstance().Lessons.Clear();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("{0}={1}&", "who", "student");
            stringBuilder.AppendFormat("{0}={1}&", "id", this.UserNameTextBox.Text);
            stringBuilder.AppendFormat("{0}={1}&", "pwd", this.UserPasswordBox.Password);
            stringBuilder.AppendFormat("{0}={1}&", "yzm", this.GenTextBox.Text);
            stringBuilder.AppendFormat("{0}={1}", "submit", @"%C8%B7+%B6%A8");

            Encoding encoding = Encoding.GetEncoding("gb2312");

            byte[] data = encoding.GetBytes(stringBuilder.ToString());

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FilePath.GetInstance().LogInRequestUri);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = this.cookieContainer;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            request = (HttpWebRequest)WebRequest.Create(FilePath.GetInstance().LessonsUri);
            request.CookieContainer = this.cookieContainer;

            response = (HttpWebResponse)request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            {

                HtmlDocument document = new HtmlDocument();

                document.Load(this.convertToMemoryStream(responseStream), Encoding.GetEncoding("gb2312"));

                HtmlNode rootNode = document.DocumentNode;

                HtmlNodeCollection lessonNodes = rootNode.SelectNodes("//tr[@class = 'TR_BODY'][position()>3]");

                foreach (HtmlNode lessonNode in lessonNodes)
                {

                    HtmlNodeCollection infos = HtmlNode.CreateNode(lessonNode.InnerHtml).SelectNodes("//td");

                    Lesson lesson = new Lesson(infos);

                    BindingSource.GetInstance().Lessons.Add(lesson);

                }

                this.Close();
            }
        }

    }

#endregion

}
